<script setup lang="ts">
import { ref, onMounted } from 'vue'

import type { FormInstance } from 'element-plus'
import { AiliPay, type PayClass } from "@/service/pay.ts"

const formRef = ref<FormInstance | null>(null)
const payDto = ref<PayClass>({
  tradeNo: Math.random() * 1000,
  totalAmount: 0,
  subject: '',
  body: ''
})

const submitForm = async () => {
  const formEl = formRef.value
  console.log('submitForm called')
  if (!formEl) {
    console.error('formEl is undefined')
    return
  }
  console.log('formEl is defined')
  formEl.validate((valid) => {
    if (valid) {
      pay();
    } else {
      console.log('error submit!')
    }
  })
}

const pay = async ()=>{
  const {data}  =await AiliPay(payDto.value);
  // 创建一个临时的 div 元素来存放返回的表单
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = data
  // 获取表单元素
  const form = tempDiv.querySelector('form')
  if (form) {
    // 将表单插入到页面中
    document.body.appendChild(form)
    // 提交表单
    form.submit()
  } else {
    console.error('Form not found in the response')
  }
}

const resetForm = () => {
  const formEl = formRef.value
  if (!formEl) return
  formEl.resetFields()
}

// 检查 formRef 是否正确初始化
onMounted(() => {
  console.log('formRef:', formRef.value)
})
</script>

<template>
  <div style="width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; background: #99d5ff">
    <el-form
      ref="formRef"
      style="max-width: 600px"
      :model="payDto"
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="商户号" prop="tradeNo">
        <el-input v-model.number="payDto.tradeNo" type="text" autocomplete="off" disabled />
      </el-form-item>
      <el-form-item
        label="支付金额"
        prop="totalAmount"
        :rules="[
          { required: true, message: '支付金额是必填项' },
          { type: 'number', message: '支付金额必须是数字' }
        ]"
      >
        <el-input v-model.number="payDto.totalAmount" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品标题" prop="subject">
        <el-input v-model="payDto.subject" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品描述" prop="body">
        <el-input v-model="payDto.body" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">Submit</el-button>
        <el-button @click="resetForm">Reset</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
</style>